package com.ahui.ydd.service.impl;

import com.ahui.ydd.Vo.*;
import com.ahui.ydd.common.CustomException;
import com.ahui.ydd.common.ResultData;
import com.ahui.ydd.dto.UserNumDto;
import com.ahui.ydd.entity.*;
import com.ahui.ydd.mapper.LoginMapper;
import com.ahui.ydd.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLWarning;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, SysUser> implements LoginService {

    @Autowired //用户
    private SysUserSerive sysUserSerive;
    @Autowired //权限
    private SysRoleService sysRoleService;
    @Autowired //权限==>菜单
    private SysRoleMenuService sysRoleMenuService;
    @Autowired //菜单
    private SysMenuService sysMenuService;
    @Autowired //字典
    private SysDictService sysDictService;
    @Autowired //配置
    private SysConfigService sysConfigService;
    @Autowired //分类
    private YddCateService yddCateService;
    @Autowired //标签
    private YddTagService yddTagService;
    @Autowired //链接
    private YddLinkService yddLinkService;
    @Autowired
    private SysUserSerive sysUserService;
    @Autowired
    private YddArticleService yddArticleService;
    @Autowired
    private YddAdvposService yddadvposService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddUserService yddUserService;

    /**
     * 用户访问配置文件
     *
     * @param userId
     * @return
     */
    @Override
    public ProFileVo profile(Long userId) {

        //查询用户信息
        SysUser sysUser = sysUserSerive.getById(userId);

        //select * from sys_role,sys_user where role_id = id;
        LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleLambdaQueryWrapper.eq(SysRole::getId, sysUser.getRoleId().substring(2, sysUser.getRoleId().length() - 2));
        //查询用户权限
        SysRole sysRole = sysRoleService.getOne(sysRoleLambdaQueryWrapper);
        //角色名称 用SysUserVo封装  复制sysUser中数据到 userInfo中
        SysUserVo userInfo = new SysUserVo();
        BeanUtils.copyProperties(sysUser, userInfo);
        userInfo.setRolename(sysRole.getName());


        //查询用户有权访问的 菜单信息
        //select menu_id from sys_role_menu,sys_role where role_id = id;
        LambdaQueryWrapper<SysRoleMenu> sysRoleMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleMenuLambdaQueryWrapper
                .select(SysRoleMenu::getMenuId)
                .eq(SysRoleMenu::getRoleId, sysRole.getId());
        List<Object> MenuIdList = sysRoleMenuService.listObjs(sysRoleMenuLambdaQueryWrapper);
        //存放菜单信息
        List<SysMenu> menuList = new ArrayList<>();
        for (Object menuId : MenuIdList) {
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getId, menuId);
            List<SysMenu> list = sysMenuService.list(queryWrapper);
            //将查到的数据一个一个存入menuList
            for (SysMenu menu : list) {
                menuList.add(menu);
            }
        }

        //查询字典表 select 返回特定的几个字段 select(字段…)
        //select type,value from sys_dict group by type;
        LambdaQueryWrapper<SysDict> sysDictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysDictLambdaQueryWrapper
                .select(SysDict::getType)
                .groupBy(SysDict::getType);
        List<Object> list = sysDictService.listObjs(sysDictLambdaQueryWrapper);
        Map<String, Map<String, String>> dictsList = new HashMap<>();
        for (Object sysDictTYpe : list) {
            HashMap<String, String> map = new HashMap<>();

            //根据type 查询数据
            LambdaQueryWrapper<SysDict> queryWrapper = new LambdaQueryWrapper<>();
            sysDictLambdaQueryWrapper
                    .eq(SysDict::getType, sysDictTYpe);
            List<SysDict> dictList = sysDictService.list(queryWrapper);
            //将查出的value 和 lable 存入map集合
            for (SysDict dict : dictList) {
                map.put(dict.getValue(), dict.getLabel());
            }
            //将所有数据存入dictsList
            dictsList.put((String) sysDictTYpe, map);
        }

        ProFileVo proFileVo = new ProFileVo();
        proFileVo.setUserInfo(userInfo);
        proFileVo.setMenuList(menuList);
        proFileVo.setDictsList(dictsList);
        proFileVo.setBtnList(sysRole.getName());

        return proFileVo;
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public IndexVo selectIndex() {

        //按照 group_value 分组查询 group_value
        //select group_value,tab_value from sys_config group by group_value
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysConfig::getGroupValue, SysConfig::getTabValue)
                .groupBy(SysConfig::getGroupValue);
        List<SysConfig> list = sysConfigService.list(queryWrapper);

        //将 group_value 复制给ChildrenVo的name
        List<ChildrenVo> childrenVos = list.stream().map((config) -> {
            //SELECT * FROM sys_config WHERE group_value = ?
            //按 group_value 条件进行查找 可以查到 group_value 对应的所有数据
            LambdaQueryWrapper<SysConfig> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysConfig::getGroupValue, config.getGroupValue());
            List<SysConfig> list1 = sysConfigService.list(queryWrapper1);

            //将list1中查到 SysConfig 数据 添加到 ChildrenVo 中
            ChildrenVo childrenVo = new ChildrenVo();
            childrenVo.setName(config.getGroupValue());
            childrenVo.setData(list1);

            return childrenVo;
        }).collect(Collectors.toList());

        //按照 tab_value 分组查询 tab_value
        //select group_value,tab_value from sys_config group by tab_value
        LambdaQueryWrapper<SysConfig> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.select(SysConfig::getGroupValue, SysConfig::getTabValue)
                .groupBy(SysConfig::getTabValue);
        List<SysConfig> list2 = sysConfigService.list(queryWrapper2);

        //将list里的 group_value,tab_value 数据添加到 SysConfigVo 中
        List<SysConfigVo> sysConfigVos = list2.stream().map((item) -> {
            SysConfigVo sysConfigVo = new SysConfigVo();
            sysConfigVo.setKey(item.getTabValue());

            if (item.getTabValue().equals("base")) {
                sysConfigVo.setName("基础配置");
            } else if (item.getTabValue().equals("system")) {
                sysConfigVo.setName("系统设置");
            } else {
                sysConfigVo.setName("其他设置");
            }

            ArrayList<ChildrenVo> sysConfigs = new ArrayList<>();
            for (ChildrenVo sysConfig : childrenVos) {
                for (SysConfig data : sysConfig.getData()) {
                    if (data.getTabValue().equals(item.getTabValue())) {
                        sysConfigs.remove(sysConfig);
                        //将数据封装到 sysConfigs 中
                        sysConfigs.add(sysConfig);
                    }
                }
            }
            if (sysConfigs.toString() != null) {
                sysConfigVo.setChildren(sysConfigs);
            }

            return sysConfigVo;
        }).collect(Collectors.toList());



        //allData
        List<SysConfig> configs = sysConfigService.list();

        //封装收集的数据添加到 返回数据的对象中
        Map<String, List> map = new HashMap<>();
        map.put("list", sysConfigVos);
        map.put("allData", configs);

        //查询所有分类
        List<YddCate> allCate = yddCateService.list();

        //查询所有标签
        List<YddTag> allTAg = yddTagService.list();

        //查询所有友情链接（文字和图片）
        List<YddLink> allLink = yddLinkService.list();

        //查询yddA_dvimg
        List<YddAdvimg> yddAdvimgList = yddAdvimgService.list();

        List<YddAdvimg> showBanner = new ArrayList<>();
        List<YddAdvimg> sideBanner = new ArrayList<>();
        List<YddAdvimg> banner = new ArrayList<>();

        for (YddAdvimg yddAdvimg : yddAdvimgList) {
            String advimgpos = yddAdvimg.getAdvimgpos();

            switch (advimgpos) {
                case "12":
                    showBanner.add(yddAdvimg);//查询详情广告图
                    break;
                case "13":
                    sideBanner.add(yddAdvimg);//查询详情广告图
                    break;
                case "14":
                    sideBanner.add(yddAdvimg);//查询侧边栏图片
                    break;
                case "15":
                    banner.add(yddAdvimg);//轮播图数据
                    break;
                default:
                    throw new CustomException("没有这个广告位");
            }
        }

        //返回数据对象
        IndexVo indexVo = new IndexVo();
        indexVo.setAllCate(allCate);
        indexVo.setConfig(map);
        indexVo.setAllTAg(allTAg);
        indexVo.setAllLink(allLink);
        indexVo.setBanner(banner);
        indexVo.setShowBanner(showBanner);
        indexVo.setSideBanner(sideBanner);

        return indexVo;
    }

    @Override
    public ResultData baseInfo() {
        BaseInfoVo baseInfoVo = new BaseInfoVo();
        //所有分类数据
        List<YddCate> yddCates = yddCateService.list();
        //获取对应分类下的文章数量
        for (YddCate yddCate : yddCates) {
            LambdaQueryWrapper<YddArticle> yddWrapper = new LambdaQueryWrapper<>();
            yddWrapper.eq(YddArticle::getCateid, yddCate.getId());
            List<YddArticle> articles = yddArticleService.list(yddWrapper);
            yddCate.setNum(articles.size());
        }
        baseInfoVo.setAll_cate(yddCates);

        //获取广告位数量
        List<YddAdvpos> advposList = yddadvposService.list();
        baseInfoVo.setAdvpos_num(advposList.size());
        //标签总数
        List<YddTag> tagList = yddTagService.list();
        baseInfoVo.setTag_num(tagList.size());
        //管理员总数
        List<SysUser> userList = sysUserService.list();
        baseInfoVo.setAdmin_num(userList.size());
        //文章总数
        List<YddArticle> articleList = yddArticleService.list();
        baseInfoVo.setArticle_num(articleList.size());
        //分类总数
        baseInfoVo.setCate_num(yddCates.size());
        //广告图总数
        List<YddAdvimg> yddAdvimgList = yddAdvimgService.list();
        baseInfoVo.setAdvimg_num(yddAdvimgList.size());

        //最新用户信息
        Page page = new Page(1, 7);
        LambdaQueryWrapper<YddUser> userLqw = new LambdaQueryWrapper<>();
        userLqw.orderByDesc(YddUser::getId);
//        List<YddUser> yddUserList = yddUserService.list(userLqw);
        Page pageInfo = yddUserService.page(page, userLqw);
        List<YddUser> yddUserList = pageInfo.getRecords();
        baseInfoVo.setNew_user(yddUserList);

        //热门文章数据
        LambdaQueryWrapper<YddArticle> articleLqw = new LambdaQueryWrapper<>();
        articleLqw.orderByDesc(YddArticle::getLovenum);
        Page pages = yddArticleService.page(page, articleLqw);
        List<YddArticle> yddArticleList = pages.getRecords();
        baseInfoVo.setHot_article(yddArticleList);

        //用户数据
        LambdaQueryWrapper<YddUser> yddLqw = new LambdaQueryWrapper<>();
        List<YddUser> list = yddUserService.list(yddLqw);
        yddLqw.eq(YddUser::getSex, 1);
        List<YddUser> manList = yddUserService.list(yddLqw);
        UserNumDto userNumDto = new UserNumDto();
        userNumDto.setTotal(list.size());
        userNumDto.setUser_man(manList.size());
        userNumDto.setUser_woman(list.size() - manList.size());
        baseInfoVo.setUser(userNumDto);

        return ResultData.ok("", baseInfoVo);
    }
}
